import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8123/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('发送请求:', config)
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('收到响应:', response)
    return response
  },
  (error) => {
    console.error('响应错误:', error)
    return Promise.reject(error)
  }
)

// 语音聊天请求接口
export interface VoiceChatRequest {
  audioUrl?: string
  audioBase64?: string
  sessionId?: string
  userId?: string
  textInput?: string
}

// 语音聊天响应接口
export interface VoiceChatResponse {
  recognizedText?: string
  aiResponse?: string
  audioBase64?: string
  sessionId?: string
  status: string
  errorMessage?: string
  processingTime?: number
}

// API响应包装接口
export interface ApiResponse<T> {
  code: number
  message: string
  data: T
  timestamp: string
  traceId?: string
  processingTime?: number
}

// 语音聊天API
export const voiceChatApi = {
  // 语音聊天 - 同步
  chat: (request: VoiceChatRequest): Promise<VoiceChatResponse> => {
    return api.post('/chat/voice', request).then(response => {
      const apiResponse = response.data as ApiResponse<VoiceChatResponse>
      if (apiResponse.code === 200 && apiResponse.data) {
        return apiResponse.data
      } else {
        throw new Error(apiResponse.message || '请求失败')
      }
    })
  },

  // 语音聊天 - 异步
  chatAsync: (request: VoiceChatRequest): Promise<VoiceChatResponse> => {
    return api.post('/chat/voice/async', request).then(response => {
      const apiResponse = response.data as ApiResponse<any>
      if (apiResponse.code === 200 && apiResponse.data) {
        return apiResponse.data
      } else {
        throw new Error(apiResponse.message || '请求失败')
      }
    })
  },

  // 健康检查
  health: (): Promise<string> => {
    return api.get('/chat/health').then(response => {
      const apiResponse = response.data as ApiResponse<string>
      if (apiResponse.code === 200 && apiResponse.data) {
        return apiResponse.data
      } else {
        throw new Error(apiResponse.message || '健康检查失败')
      }
    })
  },
}

// WebSocket连接类
export class VoiceChatWebSocket {
  private ws: WebSocket | null = null
  private url: string
  private listeners: Map<string, Function[]> = new Map()
  
  // 音频流式传输状态
  private audioStreamBuffer: Map<string, {
    totalChunks: number
    receivedChunks: Map<number, string>
    metadata?: any
    messageType?: string
  }> = new Map()

  constructor(url: string = 'ws://localhost:8123/api/ws/voice-chat') {
    this.url = url
  }

  // 连接WebSocket
  connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      try {
        console.log('正在连接WebSocket:', this.url)
        this.ws = new WebSocket(this.url)

        // 设置连接超时
        const timeout = setTimeout(() => {
          if (this.ws && this.ws.readyState === WebSocket.CONNECTING) {
            this.ws.close()
            reject(new Error('WebSocket连接超时'))
          }
        }, 10000) // 10秒超时

        this.ws.onopen = () => {
          clearTimeout(timeout)
          console.log('WebSocket连接已建立')
          this.emit('connected')
          resolve()
        }

        this.ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            console.log('收到WebSocket消息:', data)
            
            // 处理音频流式传输消息
            if (this.handleAudioStreamMessage(data)) {
              return
            }
            
            this.emit('message', data)
            
            // 根据消息类型触发特定事件
            if (data.type) {
              this.emit(data.type, data)
            }
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }

        this.ws.onerror = (error) => {
          clearTimeout(timeout)
          console.error('WebSocket错误详情:', {
            error,
            readyState: this.ws?.readyState,
            url: this.url
          })
          
          // 创建更详细的错误信息
          const errorInfo = {
            message: 'WebSocket连接失败',
            reason: this.ws?.readyState === WebSocket.CONNECTING ? '连接被拒绝' : '连接错误',
            url: this.url,
            readyState: this.ws?.readyState
          }
          
          this.emit('error', errorInfo)
          reject(errorInfo)
        }

        this.ws.onclose = (event) => {
          clearTimeout(timeout)
          console.log('WebSocket连接已关闭:', {
            code: event.code,
            reason: event.reason,
            wasClean: event.wasClean
          })
          
          const closeInfo = {
            code: event.code,
            reason: event.reason || '连接关闭',
            wasClean: event.wasClean
          }
          
          this.emit('disconnected', closeInfo)
          this.ws = null
        }
      } catch (error) {
        console.error('创建WebSocket失败:', error)
        reject(error)
      }
    })
  }

  // 发送消息
  send(data: any): boolean {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      try {
        this.ws.send(JSON.stringify(data))
        return true
      } catch (error) {
        console.error('发送WebSocket消息失败:', error)
        return false
      }
    }
    console.warn('WebSocket未连接，无法发送消息')
    return false
  }

  // 发送语音聊天请求
  sendVoiceChat(request: VoiceChatRequest): boolean {
    return this.send(request)
  }

  // 发送音频数据
  sendAudioData(audioData: ArrayBuffer): boolean {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      try {
        this.ws.send(audioData)
        return true
      } catch (error) {
        console.error('发送音频数据失败:', error)
        return false
      }
    }
    return false
  }

  // 关闭连接
  disconnect(): void {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }

  // 添加事件监听器
  on(event: string, callback: Function): void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, [])
    }
    this.listeners.get(event)!.push(callback)
  }

  // 移除事件监听器
  off(event: string, callback?: Function): void {
    if (!callback) {
      this.listeners.delete(event)
      return
    }

    const callbacks = this.listeners.get(event)
    if (callbacks) {
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    }
  }

  // 触发事件
  private emit(event: string, data?: any): void {
    const callbacks = this.listeners.get(event)
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('事件回调执行失败:', error)
        }
      })
    }
  }

  // 获取连接状态
  get isConnected(): boolean {
    return this.ws !== null && this.ws.readyState === WebSocket.OPEN
  }

  // 获取连接状态文本
  get connectionState(): string {
    if (!this.ws) return 'disconnected'
    
    switch (this.ws.readyState) {
      case WebSocket.CONNECTING:
        return 'connecting'
      case WebSocket.OPEN:
        return 'connected'
      case WebSocket.CLOSING:
        return 'closing'
      case WebSocket.CLOSED:
        return 'disconnected'
      default:
        return 'unknown'
    }
  }

  // 处理音频流式传输消息
  private handleAudioStreamMessage(data: any): boolean {
    const { type, sessionId } = data

    // 流式传输开始
    if (type && type.endsWith('_stream_start')) {
      console.log('音频流式传输开始:', data)
      this.audioStreamBuffer.set(sessionId, {
        totalChunks: data.totalChunks,
        receivedChunks: new Map(),
        metadata: data.metadata,
        messageType: type.replace('_stream_start', '')
      })
      return true
    }

    // 流式传输音频块
    if (type && type.endsWith('_stream_chunk')) {
      const streamInfo = this.audioStreamBuffer.get(sessionId)
      if (streamInfo) {
        streamInfo.receivedChunks.set(data.chunkIndex, data.audioChunk)
        console.log(`收到音频块 ${data.chunkIndex + 1}/${data.totalChunks}`)

        // 检查是否收到所有块
        if (streamInfo.receivedChunks.size === streamInfo.totalChunks) {
          this.assembleStreamedAudio(sessionId, streamInfo)
        }
      }
      return true
    }

    // 流式传输结束
    if (type && type.endsWith('_stream_end')) {
      console.log('音频流式传输结束:', sessionId)
      this.audioStreamBuffer.delete(sessionId)
      return true
    }

    // 流式传输错误
    if (type === 'audio_stream_error') {
      console.error('音频流式传输错误:', data.error)
      this.audioStreamBuffer.delete(sessionId)
      this.emit('audio_stream_error', data)
      return true
    }

    return false
  }

  // 组装流式音频数据
  private assembleStreamedAudio(sessionId: string, streamInfo: any) {
    try {
      console.log('开始组装音频流，总块数:', streamInfo.totalChunks)
      
      // 按索引顺序组装音频块
      let completeAudio = ''
      for (let i = 0; i < streamInfo.totalChunks; i++) {
        const chunk = streamInfo.receivedChunks.get(i)
        if (chunk) {
          completeAudio += chunk
        } else {
          console.error(`缺少音频块 ${i}`)
          return
        }
      }

      console.log('音频流组装完成，总大小:', completeAudio.length)

      // 创建完整的响应对象
      const completeResponse = {
        type: streamInfo.messageType,
        sessionId: sessionId,
        audioBase64: completeAudio,
        isStreaming: true,
        metadata: streamInfo.metadata
      }

      // 触发完整音频事件
      this.emit(streamInfo.messageType, completeResponse)
      
      // 清理缓冲区
      this.audioStreamBuffer.delete(sessionId)

    } catch (error) {
      console.error('组装音频流失败:', error)
      this.audioStreamBuffer.delete(sessionId)
    }
  }
}

export default api
